package util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
在界面初始化时创建文件信息数据表
 */
public class DBInit {
    //从resources路径下读取init.sql文件，加载到程序中
    public static List<String> readSQL() {
        List<String> ret = new ArrayList<>();
        InputStream in = DBInit.class.getClassLoader().
                getResourceAsStream("init.sql");
        Scanner scanner = new Scanner(in);
        scanner.useDelimiter(";");
        while(scanner.hasNext()) {
            String str = scanner.next();
            if("".equals(str) || "\n".equals(str)) continue;
            if(str.contains("--")) {
                str = str.replaceAll("--","");
            }
            ret.add(str);
        }
        return ret;
    }

    /**
     * 在界面初始化时初始化数据库，创建数据表
     */
    public static void init() {
        Connection connection = null;
        Statement statement = null;
        try {
            connection = DBUtil.getConnection();
            List<String> sqls = readSQL();
            statement = connection.createStatement();
            for (String sql : sqls) {
                System.out.println("执行SQL操作语句：" +sql);
                statement.executeUpdate(sql);
            }
        } catch (SQLException e) {
            System.out.println("数据初始化失败");
            e.printStackTrace();
        } finally {
            DBUtil.close(statement);
        }
    }

    public static void main(String[] args) {
        init();
    }
}

